/**
 * @file 学部看板报表
 * @author ruanairuo(ruanairuo@baijia.com)
 * @date 2020-03-18
 */
import React, {useState, useEffect, useRef} from 'react';
import {Card, Row, Col} from 'antd';
import CommonSearchBar from '~/page/FineBi/common/CommonSearchBar';
import DetailModal from '~/page/FineBi/common/DetailModal';
import {querySelectOptions, queryDetail, download} from '~/service/refundReport';
import {convertSearcherParams, toLine} from '~/page/FineBi/utils/convert';
import uuid from '~/utils/uuid';
import {userRoundIdx, initUserRoundIdx} from '~/utils/const';
import DynamicTable from './dynamicTable';
import {searchForm, initialValues, getDefaultDimension} from './config';

const SELECT_UNIT_ID = 'DepartmentDimensionReport_PartTen_select';
const unitId = 'DepartmentDimensionReport_PartTen_excel';
const dId = 'DepartmentDimensionReport_PartTen';
const maxDepth = 5;
const level = 2;

export default function Lecturer(props) {
    const initDemenstion = (getDefaultDimension(SELECT_UNIT_ID))
        .concat(props.initPropDimensionAndValues);
    const [loading, setLoading] = useState(false);
    const [selectOptions, setSelectOptions] = useState({});
    // 共同查询条件
    const [dimensionAndValues, setDimensionAndValues] = useState(initDemenstion);
    const [modalVisible, setModalVisible] = useState(false);
    const [detailData, setDetailData] = useState({});
    const [searchValues, setSearchValues] = useState(initDemenstion);
    const formRef = useRef();

    useEffect(() => {
        const findItem = initDemenstion.find(item => item.dimensionName === userRoundIdx);
        findItem.value = [props.userRoundValue];

        setDimensionAndValues([...initDemenstion]);

        formRef.current.formFields.resetFields();
    }, [props.userRoundValue]);

    const handleOk = fieldsValue => {
        const params = convertSearcherParams(fieldsValue, SELECT_UNIT_ID);
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    const handleReset = e => {
        const params = initDemenstion;
        setDimensionAndValues([...params, {...props.initPropDimensionAndValues[0], value: [props.userRoundValue]}]);
    };

    // 选项查询
    const handleFetchOptions = options => {
        const {key, searchKey, pager, isGetingMore, options: curOptions, fieldsValue} = options;
        let permissions = searchForm.map(item => ({
            dimensionId: `${SELECT_UNIT_ID}_${toLine(item.key)}`,
            dimensionName: toLine(item.key),
            filterItems: Array.isArray(fieldsValue[item.key])
                ? fieldsValue[item.key]
                : fieldsValue[item.key] == null
                    ? []
                    : [fieldsValue[item.key]]
        }));

        permissions = permissions.filter(item => (item.filterItems?.length && item.dimensionName !== userRoundIdx));
        permissions.push({...props.initPropDimensionAndValues[0], value: [props.userRoundValue]});

        const params = {
            pager,
            dimensionId: `${SELECT_UNIT_ID}_${toLine(key)}`,
            dimensionName: toLine(key),
            searchKey,
            permissions,
            unitId: SELECT_UNIT_ID
        };

        querySelectOptions(params).then(res => {
            const {data, pager} = res;
            let options =
                data.map(item => ({
                    key: item,
                    value: item,
                    label: item
                })) || [];
            // 分页时，累加展示
            if (isGetingMore) {
                options = curOptions.concat(options);
            }
            setSelectOptions({key, options, pager});
        });
    };

    const handleDownload = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        const params = {
            dimensionAndValues,
            unitId,
            unitName
        };
        const excelName = unitName ? unitName : null;
        download(params, excelName);
    };

    const handleDetail = (
        {unitId = '', unitName = ''} = {},
        dashBoardId = ''
    ) => () => {
        setModalVisible(true);
        const params = {
            dimensionAndValues,
            unitId,
            unitName
        };
        queryDetail(params).then(res => {
            const {data} = res;
            setDetailData(data);
        });
    };

    // 表单change
    const handleItemChange = itemKeyValue => {
        const filterValue = {...itemKeyValue};
        let dimensionValues = [...searchValues];
        for (const i in filterValue) {
            filterValue[i] = filterValue[i].filter(ele => ele !== '全部');
            formRef.current.formFields.setFieldsValue({
                [i]: filterValue[i]
            });
            dimensionValues = dimensionValues.map(ele => {
                if (ele.dimensionId === `${SELECT_UNIT_ID}_${toLine(i)}`) {
                    ele.value = filterValue[i];
                }
                return ele;
            });
        }
        setSearchValues(dimensionValues);
    };

    return (
        <div>
            <Card style={{marginBottom: 8}}>
                <CommonSearchBar
                    noCache
                    config={searchForm}
                    initialValues={initialValues}
                    onOk={handleOk}
                    onReset={handleReset}
                    onfetchOptions={handleFetchOptions}
                    selectOptions={selectOptions}
                    onItemChange={handleItemChange}
                    ref={formRef}
                />
            </Card>
            <Card>
                <Row>
                    <Col span={24}>
                        <DynamicTable
                            dimensionAndValues={dimensionAndValues}
                            unitId={unitId}
                            dId={dId}
                            // 树深度
                            maxDepth={maxDepth}
                            level={level}
                            userRoundValue={props.userRoundValue}
                        />
                    </Col>
                </Row>
            </Card>
            <DetailModal data={detailData} detailModalVisible={modalVisible} onCancel={() => setModalVisible(false)} />
        </div>
    );
}
